package peer.model.transfer.runnable;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import model.dto.FileDTO;
import peer.model.consts.TransferConsts;
import peer.model.transfer.file.FileReceiver;

public class BlockDownloadInstance implements Runnable {

	private FileDTO requestedFile;
	private int blockNumber;
	//blockSize partition_size const
	private Socket sck;
	private FileOutputStream destination;

	public BlockDownloadInstance(FileDTO requestedFile, int blockNumber, Socket sck, FileOutputStream destination){
		this.sck=sck;
		this.blockNumber=blockNumber;
		this.requestedFile=requestedFile;
		this.destination=destination;
	}

	@Override
	public void run() {
		PrintWriter pw;
		try {
			//Sending Request
			pw = new PrintWriter(sck.getOutputStream(), true);
			pw.println(requestedFile.getFilename() + "." +  requestedFile.getExtension());

			//Receiving Response
			System.out.println("[PEER/DOWNLOAD] Downloading from... " + sck.getInetAddress().toString());
			FileReceiver.receiveFile(sck, TransferConsts.DOWNLOAD_PATH, Thread.currentThread().getName());
			System.out.println("[PEER/DOWNLOAD] FINISHED");
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}finally{
			try{
				sck.close();
			}catch(IOException e){
				e.printStackTrace(System.err);
			}
		}

	}

}
